package com.ruicar.afs.cloud.manage.cms.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.dispatch.contract.CmsInterfaceFeign;
import com.ruicar.afs.cloud.basic.api.dto.BasicMainInfoDto;
import com.ruicar.afs.cloud.basic.api.dto.CustContactVO;
import com.ruicar.afs.cloud.basic.api.fegin.info.BasicInfoFeign;
import com.ruicar.afs.cloud.bizcommon.cms.dto.*;
import com.ruicar.afs.cloud.bizcommon.cms.dtoresponse.CmsContractOneInfoDTO;
import com.ruicar.afs.cloud.bizcommon.cms.dtoresponse.CmsCustomerAddressList;
import com.ruicar.afs.cloud.bizcommon.cms.enums.CodeResponseEnum;
import com.ruicar.afs.cloud.bizcommon.cms.enums.SuccessResponseEnum;
import com.ruicar.afs.cloud.bizcommon.cms.feign.CmsPlanChangeFeign;
import com.ruicar.afs.cloud.common.config.ContractFeginConfig;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.AddressTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ContractFeginParamEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.PersonRoleTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.RoleEnum;
import com.ruicar.afs.cloud.manage.cms.service.IcosToCmsChangeRepaymentService;
import com.ruicar.afs.cloud.manage.common.entity.ManageBankCardChange;
import com.ruicar.afs.cloud.manage.common.entity.ManageCustInfoChange;
import com.ruicar.afs.cloud.manage.common.entity.ManageRelationChange;
import com.ruicar.afs.cloud.manage.common.entity.ManageRepaymentDateChange;
import com.ruicar.afs.cloud.manage.contractcancel.vo.ContractCancelManageVO;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysAddressParam;
import com.ruicar.afs.cloud.parameter.commom.service.TsysAddressParamService;
import lombok.AllArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description:
 */
@AllArgsConstructor
@Service
public class IcosToCmsChangeRepaymentServiceImpl implements IcosToCmsChangeRepaymentService {

    private CmsPlanChangeFeign cmsPlanChangeFeign;
    private final BasicInfoFeign basicInfoFeign;
    private final CmsInterfaceFeign cmsInterfaceFeign;
    private final ContractFeginConfig contractFeginConfig;
    private final TsysAddressParamService service;

    @Override
    public CmsResponse syncToCmsChangeRepaymentResult(ManageRepaymentDateChange change) {
        CmsChangeRepaymentRequestDTO dto = new CmsChangeRepaymentRequestDTO();
        dto.setRequestId(String.valueOf(change.getId()));
        dto.setApplicationNo(change.getContractNo());
        dto.setOperatorUser(change.getCreateBy());
        dto.setApprover(change.getCreateBy());
        return cmsPlanChangeFeign.changeRepayment(dto);
    }
//
//    @Override
//    public CmsBaseResponseDTO syncToCmsContractCloseResult(ManageOverpaymentDifference difference) {
//        CmsContractCloseRequestDTO dto = new CmsContractCloseRequestDTO();
//////        dto.setRequestId(String.valueOf(difference.getId()));
//////        dto.setApplicationNo(difference.getContractNo());
//////        dto.setOperatorUser(difference.getCreateBy());
//////        dto.setApprover(difference.getCreateBy());
////        return cmsPlanChangeFeign.contractClose(dto);
//        return dto;
//    }

    @Override
    public CmsResponse syncToCmsContractCancelResult(ContractCancelManageVO contractStatusDto) {
        CmsCancelContractRequestDto dto = new CmsCancelContractRequestDto();
        dto.setRequestId(String.valueOf(contractStatusDto.getId()));
        dto.setApplicationNo(contractStatusDto.getContractNo());
        dto.setOperatorUser(contractStatusDto.getCreateBy());
        dto.setApprover(contractStatusDto.getCreateBy());
        IResponse<BasicMainInfoDto> basicMainInfoDtoIResponse = basicInfoFeign.mainInfofindByContractNo(contractStatusDto.getContractNo());
        dto.setContractId(String.valueOf(basicMainInfoDtoIResponse.getData().getId()));
        dto.setReceiptAmt(contractStatusDto.getAmount());
        dto.setReceiptDate(contractStatusDto.getAccountDate());
        Map<String, String> headers = new HashMap<>();
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.MANAGE_CLIENT_SECRET), contractFeginConfig.getManageClientSecret());
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.MANAGE_CLIENT_ID), contractFeginConfig.getManageClientId());
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.CONTENT_TYPE), MediaType.APPLICATION_JSON_VALUE);
        IResponse<String> witnessInfo = cmsInterfaceFeign.getWitnessInfo(contractStatusDto.getContractNo(), headers);
//        dto.setInsertedBy(witnessInfo.getData());
        dto.setInsertedBy("dhzg");
        return cmsPlanChangeFeign.ContractCancel(dto);
    }

    @Override
    public CmsResponse syncToCmsChangeCustInfoResult(ManageCustInfoChange change) {
        CmsChangeCustInfoRequestDTO dto = new CmsChangeCustInfoRequestDTO();
        dto.setApplicationNo(change.getApplyNo());//申请号
        dto.setApprover(change.getUpdateBy());//审批人
        dto.setCertDeadline(change.getNewCertEndDate());//到期日
        dto.setCertNo(change.getNewCertNo());//证件号
        dto.setCertType(change.getNewCertType());//证件类型
        dto.setName(change.getNewName());//姓名
        dto.setOperatorUser(change.getApplyBy());//操作人
        dto.setOrigin("icos");//来源
        dto.setRequestId(change.getId().toString());//外围系统存储id
        //角色编码（主借人00003，共借人00004，担保人00005）
        if (change.getChangeSubject().equals(PersonRoleTypeEnum.MAIN_PERSON)) {
            dto.setRoleCode("00003");
        } else if (change.getChangeSubject().equals(PersonRoleTypeEnum.JOINT_PERSON)) {
            dto.setRoleCode("00004");
        } else {
            dto.setRoleCode("00005");
        }
        return cmsPlanChangeFeign.changeCustInfo(dto);
    }


    @Override
    public CmsResponse syncToCmsChangeBankCardResult(ManageBankCardChange bankCardInfo) {
        CmsChangeBankCardRequestDTO dto = new CmsChangeBankCardRequestDTO();
        dto.setAccountName(bankCardInfo.getNewCardholder());
        dto.setAccountNo(bankCardInfo.getNewBankAccount());
        dto.setApplicationNo(bankCardInfo.getApplyNo());
        dto.setApprover(bankCardInfo.getCreateBy());
        dto.setBank(bankCardInfo.getNewBank());
        dto.setBranch("103");
        dto.setOperatorUser(bankCardInfo.getUpdateBy());
        dto.setOrigin("icos");
        dto.setRequestId(String.valueOf(bankCardInfo.getId()));
        return cmsPlanChangeFeign.changeBankAccountToCms(dto);
    }

    @Override
    public CmsResponse syncToCmsPhoneResult(ManageRelationChange contactChange) {
        CmsRelationChangeRequestDTO dto = publicWay(contactChange);
        String changeInfoJson = contactChange.getChangeInfoJson();
        CustContactVO custContactVO = JSON.parseObject(changeInfoJson, CustContactVO.class);
        dto.setApplicationPhone(custContactVO.getNewPhone());
        //翻譯
        dto.setRole(null);
        if (contactChange.getChangeSubject().equals(PersonRoleTypeEnum.MAIN_PERSON)) {
            dto.setRole("00003");
        } else if (contactChange.getChangeSubject().equals(PersonRoleTypeEnum.JOINT_PERSON)) {
            dto.setRole("00004");
        } else if (contactChange.getChangeSubject().equals(PersonRoleTypeEnum.GUARANTEE_PERSON)) {
            dto.setRole("00005");
        }

        return cmsPlanChangeFeign.syncToCmsPhoneResult(dto);
    }

    @Override
    public CmsResponse syncToCmsAddressResult(ManageRelationChange contactChange) {
        String changeInfoJson = contactChange.getChangeInfoJson();
        CustContactVO custContactVO = JSON.parseObject(changeInfoJson, CustContactVO.class);
        String role = null;
        if (contactChange.getChangeSubject().equals(PersonRoleTypeEnum.MAIN_PERSON)) {
            role = "00003";
        } else if (contactChange.getChangeSubject().equals(PersonRoleTypeEnum.JOINT_PERSON)) {
            role = "00004";
        } else if (contactChange.getChangeSubject().equals(PersonRoleTypeEnum.GUARANTEE_PERSON)) {
            role = "00005";
        }
        //获取CMS的房产累心
        CmsContractDTO cmsContractDTO = new CmsContractDTO();
        cmsContractDTO.setRoleCode(role);
        cmsContractDTO.setApplicationNo(contactChange.getApplyNo());
        CmsResponse<CmsContractOneInfoDTO> cmsContractOneInfoDTOCmsResponse = cmsPlanChangeFeign.syncToCmsCustomer(cmsContractDTO);
        String newHomeAddressType ="";
        String newWorkAddressType ="";
        String newLiveAddressType ="";
        String newMailingAddressType ="";
        for (CmsCustomerAddressList cmsCustomerAddressList : cmsContractOneInfoDTOCmsResponse.getData().getCustomerAddressList()) {


            if (cmsCustomerAddressList.getAddressTypeCode().equals("00006")){
                newHomeAddressType = cmsCustomerAddressList.getHouseType();
            }else if (cmsCustomerAddressList.getAddressTypeCode().equals("00003")){
                newWorkAddressType = cmsCustomerAddressList.getHouseType();
            }else if (cmsCustomerAddressList.getAddressTypeCode().equals("00002")){
                newLiveAddressType = cmsCustomerAddressList.getHouseType();
            }else if (cmsCustomerAddressList.getAddressTypeCode().equals("00001")){
                newMailingAddressType = cmsCustomerAddressList.getHouseType();
            }
        }
        CmsResponse cmsResponse = new CmsResponse();
        if (custContactVO.getNewHomeAddress() != null && custContactVO.getNewWorkAddress().length > 0) {


            CmsRelationChangeRequestDTO dto = publicWay(contactChange);
            dto.setAddressType("00006");
            //翻譯
            dto.setRole(role);

            String[] newHomeAddress = custContactVO.getNewHomeAddress();
            TsysAddressParam pro = null;
            TsysAddressParam city = null;
            if (newHomeAddress[0] != null) {
                pro = service.getOne(Wrappers.<TsysAddressParam>query().lambda().eq(
                        TsysAddressParam::getValue, newHomeAddress[0]
                ));
            }
            if (newHomeAddress[0] != null) {
                city = service.getOne(Wrappers.<TsysAddressParam>query().lambda().eq(
                        TsysAddressParam::getValue, newHomeAddress[1]
                ));
            }
            dto.setPropertyType(newHomeAddressType);

            if (newHomeAddressType==null&&newHomeAddressType==""){
                throw new AfsBaseException("由于CMS系统缺失房产类型,地址变更结果数据推送至cms系统失败，请重试！");
            }
            cmsResponse = addresssString(custContactVO, dto, pro, city);

        }
        if (custContactVO.getNewWorkAddress() != null && custContactVO.getNewWorkAddress().length > 0) {
            CmsRelationChangeRequestDTO dto = publicWay(contactChange);
            dto.setAddressType("00003");
            //翻譯
            dto.setRole(role);

            String[] newWorkAddress = custContactVO.getNewWorkAddress();
            TsysAddressParam pro = null;
            TsysAddressParam city = null;
            if (newWorkAddress[0] != null) {
                pro = service.getOne(Wrappers.<TsysAddressParam>query().lambda().eq(
                        TsysAddressParam::getValue, newWorkAddress[0]
                ));
            }
            if (newWorkAddress[0] != null) {
                city = service.getOne(Wrappers.<TsysAddressParam>query().lambda().eq(
                        TsysAddressParam::getValue, newWorkAddress[1]
                ));
            }
            dto.setPropertyType(newWorkAddressType);
            if (newWorkAddressType==null&&newWorkAddressType==""){
                throw new AfsBaseException("由于CMS系统缺失房产类型,地址变更结果数据推送至cms系统失败，请重试！");
            }
            cmsResponse = addresssString(custContactVO, dto, pro, city);
        }
        if (custContactVO.getNewLiveAddress() != null && custContactVO.getNewLiveAddress().length > 0) {
            CmsRelationChangeRequestDTO dto = publicWay(contactChange);
            dto.setAddressType("00002");
            //翻譯
            dto.setRole(role);

            String[] newLiveAddress = custContactVO.getNewLiveAddress();
            TsysAddressParam pro = null;
            TsysAddressParam city = null;
            if (newLiveAddress[0] != null) {
                pro = service.getOne(Wrappers.<TsysAddressParam>query().lambda().eq(
                        TsysAddressParam::getValue, newLiveAddress[0]
                ));
            }
            if (newLiveAddress[0] != null) {
                city = service.getOne(Wrappers.<TsysAddressParam>query().lambda().eq(
                        TsysAddressParam::getValue, newLiveAddress[1]
                ));
            }
            dto.setPropertyType(newLiveAddressType);
            if (newLiveAddressType==null&&newLiveAddressType==""){
                throw new AfsBaseException("由于CMS系统缺失房产类型,地址变更结果数据推送至cms系统失败，请重试！");
            }
            cmsResponse = addresssString(custContactVO, dto, pro, city);
        }
        if (custContactVO.getNewMailingAddress() != null && custContactVO.getNewMailingAddress().length > 0) {
            CmsRelationChangeRequestDTO dto = publicWay(contactChange);
            dto.setAddressType("00001");
            //翻譯
            dto.setRole(role);

            String[] newMailingAddress = custContactVO.getNewMailingAddress();
            TsysAddressParam pro = null;
            TsysAddressParam city = null;
            if (newMailingAddress[0] != null) {
                pro = service.getOne(Wrappers.<TsysAddressParam>query().lambda().eq(
                        TsysAddressParam::getValue, newMailingAddress[0]
                ));
            }
            if (newMailingAddress[0] != null) {
                city = service.getOne(Wrappers.<TsysAddressParam>query().lambda().eq(
                        TsysAddressParam::getValue, newMailingAddress[1]
                ));
            }
            dto.setPropertyType(newMailingAddressType);
            if (newMailingAddressType==null&&newMailingAddressType==""){
                throw new AfsBaseException("由于CMS系统缺失房产类型,地址变更结果数据推送至cms系统失败，请重试！");
            }
            cmsResponse = addresssString(custContactVO, dto, pro, city);
        }

        return cmsResponse;
    }




    private CmsRelationChangeRequestDTO publicWay(ManageRelationChange contactChange) {
        CmsRelationChangeRequestDTO dto = new CmsRelationChangeRequestDTO();
        dto.setRequestId(String.valueOf(contactChange.getId()));
        dto.setApplicationNo(contactChange.getApplyNo());
        dto.setOperatorUser(contactChange.getCreateBy());
        dto.setApprover(contactChange.getCreateBy());
        return dto;
    }

    private CmsResponse addresssString(CustContactVO custContactVO, CmsRelationChangeRequestDTO dto, TsysAddressParam pro, TsysAddressParam city) {
        CmsResponse cmsResponse;
        String label = pro.getLabel();
        String label1 = city.getLabel();
        String oldHomeAddressDetail = custContactVO.getOldHomeAddressDetail();
        StringBuffer wechat = new StringBuffer();
        StringBuffer append = wechat.append(label).append(label1).append(oldHomeAddressDetail);
        dto.setAddress(append.toString());
        cmsResponse = cmsPlanChangeFeign.syncToCmsAddressResult(dto);
        return cmsResponse;
    }
}
